/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.netbeans.modules.php.analysis.ui.options;

import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.DefaultComboBoxModel;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.LayoutStyle;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentListener;
import org.netbeans.modules.php.analysis.commands.PHPStan;
import org.netbeans.modules.php.analysis.options.AnalysisOptions;
import org.netbeans.modules.php.analysis.options.AnalysisOptionsValidator;
import org.netbeans.modules.php.analysis.ui.AnalysisDefaultDocumentListener;
import org.netbeans.modules.php.analysis.ui.PHPStanLevelListCellRenderer;
import org.netbeans.modules.php.analysis.options.ValidatorPHPStanParameter;
import org.netbeans.modules.php.analysis.util.AnalysisUiUtils;
import org.netbeans.modules.php.api.validation.ValidationResult;
import org.openide.awt.HtmlBrowser;
import org.openide.awt.Mnemonics;
import org.openide.util.ChangeSupport;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle;

public class PHPStanOptionsPanel extends AnalysisCategoryPanel {

    private static final long serialVersionUID = 1199550925948622972L;

    private final ChangeSupport changeSupport = new ChangeSupport(this);

    /**
     * Creates new form PHPStanOptionsPanel
     */
    public PHPStanOptionsPanel() {
        super();
        initComponents();
        init();
    }

    @NbBundle.Messages({
        "# {0} - short script name",
        "# {1} - long script name",
        "PHPStanOptionsPanel.hint=Full path of PHPStan script (typically {0} or {1}).",})
    private void init() {
        phpStanHintLabel.setText(Bundle.PHPStanOptionsPanel_hint(PHPStan.NAME, PHPStan.LONG_NAME));
        phpStanLevelComboBox.removeAllItems();
        // NETBEANS-2974
        // allow empty level option to use a level of a configuration file
        phpStanLevelComboBox.addItem(""); // NOI18N
        for (int i = AnalysisOptions.PHPSTAN_MIN_LEVEL; i <= AnalysisOptions.PHPSTAN_MAX_LEVEL; i++) {
            phpStanLevelComboBox.addItem(String.valueOf(i));
        }
        phpStanLevelComboBox.addItem(PHPStan.MAX_LEVEL);
        phpStanLevelComboBox.setRenderer(new PHPStanLevelListCellRenderer(phpStanLevelComboBox.getRenderer()));
        // add listener
        DocumentListener defaultDocumentListener = new AnalysisDefaultDocumentListener(() -> fireChange());
        phpStanTextField.getDocument().addDocumentListener(defaultDocumentListener);
        phpStanConfigurationTextField.getDocument().addDocumentListener(defaultDocumentListener);
        phpStanMemoryLimitTextField.getDocument().addDocumentListener(defaultDocumentListener);
        phpStanLevelComboBox.addActionListener(e -> fireChange());
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        phpStanLabel = new JLabel();
        phpStanTextField = new JTextField();
        phpStanBrowseButton = new JButton();
        phpStanSearchButton = new JButton();
        phpStanHintLabel = new JLabel();
        phpStanLevelLabel = new JLabel();
        phpStanLevelComboBox = new JComboBox<>();
        phpStanMemoryLimitLabel = new JLabel();
        phpStanMemoryLimitTextField = new JTextField();
        phpStanConfigurationLabel = new JLabel();
        phpStanConfigurationTextField = new JTextField();
        phpStanConfigurationInfoLabel = new JLabel();
        phpStanConfiturationBrowseButton = new JButton();
        phpStanNoteLabel = new JLabel();
        phpStanMinVersionInfoLabel = new JLabel();
        phpStanLearnMoreLabel = new JLabel();

        phpStanLabel.setLabelFor(phpStanTextField);
        Mnemonics.setLocalizedText(phpStanLabel, NbBundle.getMessage(PHPStanOptionsPanel.class, "PHPStanOptionsPanel.phpStanLabel.text")); // NOI18N

        Mnemonics.setLocalizedText(phpStanBrowseButton, NbBundle.getMessage(PHPStanOptionsPanel.class, "PHPStanOptionsPanel.phpStanBrowseButton.text")); // NOI18N
        phpStanBrowseButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                phpStanBrowseButtonActionPerformed(evt);
            }
        });

        Mnemonics.setLocalizedText(phpStanSearchButton, NbBundle.getMessage(PHPStanOptionsPanel.class, "PHPStanOptionsPanel.phpStanSearchButton.text")); // NOI18N
        phpStanSearchButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                phpStanSearchButtonActionPerformed(evt);
            }
        });

        Mnemonics.setLocalizedText(phpStanHintLabel, "HINT"); // NOI18N

        phpStanLevelLabel.setLabelFor(phpStanLevelComboBox);
        Mnemonics.setLocalizedText(phpStanLevelLabel, NbBundle.getMessage(PHPStanOptionsPanel.class, "PHPStanOptionsPanel.phpStanLevelLabel.text")); // NOI18N

        phpStanLevelComboBox.setModel(new DefaultComboBoxModel<>(new String[] { "0", "1", "2", "3", "4", "5", "6", "7" }));

        phpStanMemoryLimitLabel.setLabelFor(phpStanMemoryLimitTextField);
        Mnemonics.setLocalizedText(phpStanMemoryLimitLabel, NbBundle.getMessage(PHPStanOptionsPanel.class, "PHPStanOptionsPanel.phpStanMemoryLimitLabel.text")); // NOI18N

        phpStanConfigurationLabel.setLabelFor(phpStanConfigurationTextField);
        Mnemonics.setLocalizedText(phpStanConfigurationLabel, NbBundle.getMessage(PHPStanOptionsPanel.class, "PHPStanOptionsPanel.phpStanConfigurationLabel.text")); // NOI18N

        Mnemonics.setLocalizedText(phpStanConfigurationInfoLabel, NbBundle.getMessage(PHPStanOptionsPanel.class, "PHPStanOptionsPanel.phpStanConfigurationInfoLabel.text")); // NOI18N

        Mnemonics.setLocalizedText(phpStanConfiturationBrowseButton, NbBundle.getMessage(PHPStanOptionsPanel.class, "PHPStanOptionsPanel.phpStanConfiturationBrowseButton.text")); // NOI18N
        phpStanConfiturationBrowseButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                phpStanConfiturationBrowseButtonActionPerformed(evt);
            }
        });

        Mnemonics.setLocalizedText(phpStanNoteLabel, NbBundle.getMessage(PHPStanOptionsPanel.class, "PHPStanOptionsPanel.phpStanNoteLabel.text")); // NOI18N

        Mnemonics.setLocalizedText(phpStanMinVersionInfoLabel, NbBundle.getMessage(PHPStanOptionsPanel.class, "PHPStanOptionsPanel.phpStanMinVersionInfoLabel.text")); // NOI18N

        Mnemonics.setLocalizedText(phpStanLearnMoreLabel, NbBundle.getMessage(PHPStanOptionsPanel.class, "PHPStanOptionsPanel.phpStanLearnMoreLabel.text")); // NOI18N
        phpStanLearnMoreLabel.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent evt) {
                phpStanLearnMoreLabelMousePressed(evt);
            }
            public void mouseEntered(MouseEvent evt) {
                phpStanLearnMoreLabelMouseEntered(evt);
            }
        });

        GroupLayout layout = new GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(phpStanMinVersionInfoLabel)
                    .addComponent(phpStanLearnMoreLabel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(phpStanConfigurationLabel)
                    .addComponent(phpStanLabel)
                    .addComponent(phpStanLevelLabel)
                    .addComponent(phpStanNoteLabel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addComponent(phpStanMemoryLimitLabel))
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                            .addComponent(phpStanConfigurationInfoLabel)
                            .addComponent(phpStanLevelComboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                            .addComponent(phpStanMemoryLimitTextField, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 24, Short.MAX_VALUE))
                    .addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING)
                            .addComponent(phpStanConfigurationTextField)
                            .addComponent(phpStanTextField, GroupLayout.Alignment.LEADING)
                            .addGroup(GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(phpStanHintLabel)
                                .addGap(0, 0, Short.MAX_VALUE)))
                        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(phpStanBrowseButton)
                                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(phpStanSearchButton))
                            .addComponent(phpStanConfiturationBrowseButton)))))
        );
        layout.setVerticalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(phpStanLabel)
                    .addComponent(phpStanTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addComponent(phpStanBrowseButton)
                    .addComponent(phpStanSearchButton))
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(phpStanHintLabel)
                .addGap(6, 6, 6)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(phpStanConfigurationLabel)
                    .addComponent(phpStanConfigurationTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addComponent(phpStanConfiturationBrowseButton))
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(phpStanConfigurationInfoLabel)
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(phpStanLevelLabel)
                    .addComponent(phpStanLevelComboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(phpStanMemoryLimitLabel)
                    .addComponent(phpStanMemoryLimitTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(phpStanNoteLabel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(phpStanMinVersionInfoLabel)
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(phpStanLearnMoreLabel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void phpStanBrowseButtonActionPerformed(ActionEvent evt) {//GEN-FIRST:event_phpStanBrowseButtonActionPerformed
        File file = AnalysisUiUtils.browsePHPStan();
        if (file != null) {
            phpStanTextField.setText(file.getAbsolutePath());
        }
    }//GEN-LAST:event_phpStanBrowseButtonActionPerformed

    private void phpStanSearchButtonActionPerformed(ActionEvent evt) {//GEN-FIRST:event_phpStanSearchButtonActionPerformed
        String phpStan = AnalysisUiUtils.searchPHPStan();
        if (phpStan != null) {
            phpStanTextField.setText(phpStan);
        }
    }//GEN-LAST:event_phpStanSearchButtonActionPerformed

    private void phpStanLearnMoreLabelMouseEntered(MouseEvent evt) {//GEN-FIRST:event_phpStanLearnMoreLabelMouseEntered
        evt.getComponent().setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    }//GEN-LAST:event_phpStanLearnMoreLabelMouseEntered

    private void phpStanLearnMoreLabelMousePressed(MouseEvent evt) {//GEN-FIRST:event_phpStanLearnMoreLabelMousePressed
        try {
            URL url = new URL("https://github.com/phpstan/phpstan"); // NOI18N
            HtmlBrowser.URLDisplayer.getDefault().showURL(url);
        } catch (MalformedURLException ex) {
            Exceptions.printStackTrace(ex);
        }
    }//GEN-LAST:event_phpStanLearnMoreLabelMousePressed

    private void phpStanConfiturationBrowseButtonActionPerformed(ActionEvent evt) {//GEN-FIRST:event_phpStanConfiturationBrowseButtonActionPerformed
        File file = AnalysisUiUtils.browsePHPStanConfiguration();
        if (file != null) {
            phpStanConfigurationTextField.setText(file.getAbsolutePath());
        }
    }//GEN-LAST:event_phpStanConfiturationBrowseButtonActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private JButton phpStanBrowseButton;
    private JLabel phpStanConfigurationInfoLabel;
    private JLabel phpStanConfigurationLabel;
    private JTextField phpStanConfigurationTextField;
    private JButton phpStanConfiturationBrowseButton;
    private JLabel phpStanHintLabel;
    private JLabel phpStanLabel;
    private JLabel phpStanLearnMoreLabel;
    private JComboBox<String> phpStanLevelComboBox;
    private JLabel phpStanLevelLabel;
    private JLabel phpStanMemoryLimitLabel;
    private JTextField phpStanMemoryLimitTextField;
    private JLabel phpStanMinVersionInfoLabel;
    private JLabel phpStanNoteLabel;
    private JButton phpStanSearchButton;
    private JTextField phpStanTextField;
    // End of variables declaration//GEN-END:variables

    @NbBundle.Messages("PHPStanOptionsPanel.category.name=PHPStan")
    @Override
    public String getCategoryName() {
        return Bundle.PHPStanOptionsPanel_category_name();
    }

    @Override
    public void addChangeListener(ChangeListener listener) {
        changeSupport.addChangeListener(listener);
    }

    @Override
    public void removeChangeListener(ChangeListener listener) {
        changeSupport.removeChangeListener(listener);
    }

    @Override
    public void update() {
        AnalysisOptions options = AnalysisOptions.getInstance();
        setPHPStanPath(options.getPHPStanPath());
        setPHPStanConfigurationPath(options.getPHPStanConfigurationPath());
        setPHPStanLevel(options.getPHPStanLevel());
        setPHPStanMemoryLimit(options.getPHPStanMemoryLimit());
    }

    @Override
    public void applyChanges() {
        AnalysisOptions options = AnalysisOptions.getInstance();
        options.setPHPStanPath(getPHPStanPath());
        options.setPHPStanConfigurationPath(getPHPStanConfigurationPath());
        options.setPHPStanLevel(getPHPStanLevel());
        options.setPHPStanMemoryLimit(getPHPStanMemoryLimit());
    }

    @Override
    public boolean isChanged() {
        String saved = AnalysisOptions.getInstance().getPHPStanPath();
        String current = getPHPStanPath();
        if (saved == null ? !current.isEmpty() : !saved.equals(current)) {
            return true;
        }
        saved = AnalysisOptions.getInstance().getPHPStanConfigurationPath();
        current = getPHPStanConfigurationPath();
        if (saved == null ? !current.isEmpty() : !saved.equals(current)) {
            return true;
        }
        String savedString = AnalysisOptions.getInstance().getPHPStanLevel();
        String currentString = getPHPStanLevel();
        return !savedString.equals(currentString);
    }

    @Override
    public ValidationResult getValidationResult() {
        return new AnalysisOptionsValidator()
                .validatePHPStan(ValidatorPHPStanParameter.create(this))
                .getResult();
    }

    void fireChange() {
        changeSupport.fireChange();
    }

    public String getPHPStanPath() {
        return phpStanTextField.getText().trim();
    }

    private void setPHPStanPath(String path) {
        phpStanTextField.setText(path);
    }

    public String getPHPStanConfigurationPath() {
        return phpStanConfigurationTextField.getText().trim();
    }

    private void setPHPStanConfigurationPath(String path) {
        phpStanConfigurationTextField.setText(path);
    }

    public String getPHPStanLevel() {
        return (String) phpStanLevelComboBox.getSelectedItem();
    }

    private void setPHPStanLevel(String level) {
        phpStanLevelComboBox.setSelectedItem(level);
    }

    public String getPHPStanMemoryLimit() {
        return phpStanMemoryLimitTextField.getText().trim();
    }

    private void setPHPStanMemoryLimit(String memoryLimit) {
        phpStanMemoryLimitTextField.setText(memoryLimit);
    }
}
